package com.yxd.demo.util;

import com.yxd.demo.service.MarketingWayService;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.api.RulesEngineParameters;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.mvel2.ParserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

/**
 * @author: yxd
 * @date: 2022/8/1 11:51
 */
@Configuration
public class RuleEngineConfig {

    @Autowired
    private MyRulesEngineListener myRulesEngineListener;

    @Autowired
    private MyRuleListener myRuleListener;

    @Bean(value = "defaultRuleEngine")
    public RulesEngine getRulesEngine(){
        RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstAppliedRule(true);
        //RulesEngineParameters parameters = new RulesEngineParameters().skipOnFirstFailedRule(true);
        DefaultRulesEngine rulesEngine = new DefaultRulesEngine(parameters);
        rulesEngine.registerRulesEngineListener(myRulesEngineListener);
        rulesEngine.registerRuleListener(myRuleListener);
        return rulesEngine;
    }

    @Bean(value = "parserContext")
    public ParserContext getParserContext(){
        ParserContext parserContext = new ParserContext();
        Method[] declaredMethods = MarketingWayService.class.getDeclaredMethods();
        for (Method method : declaredMethods){
            parserContext.addImport(method.getName(), method);
        }
        return parserContext;
    }
}
